package com.huajin.codetest.thread.pool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolExecutorTest2 {
	
	/**
	 * 最大程度使用线程
	 * 
	 * 需要平衡阻塞队列和最大线程数与提交任务数的关系
	 *
	 * @param args
	 * @author hongwei.lian
	 * @date 2022年1月6日 下午4:45:54
	 */
	public static void main(String[] args) {
		ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(10));
		List<Future<?>> futureList = new ArrayList<>();
		for (int i = 0; i < 30; i++) {
			Future<?> future = threadPoolExecutor.submit(() -> {
				//System.out.println("execute：" + threadPoolExecutor.getCorePoolSize());
				//System.out.println("execute：" + threadPoolExecutor.getPoolSize());
				//System.out.println("execute：" + threadPoolExecutor.getQueue().size());
				for (int j = 0; j < 500; j++) {
					try {
						System.out.println("business：" + Thread.currentThread().getName());
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
			futureList.add(future);
		}
		System.out.println(threadPoolExecutor.getCorePoolSize());
		System.out.println(threadPoolExecutor.getPoolSize());
		System.out.println(threadPoolExecutor.getQueue().size());
		
		threadPoolExecutor.shutdown();
		
		
		//-- 查看任务执行结果
		for (Future<?> future : futureList) {
			try {
				Thread.sleep(5000 * 10);
				System.out.println(future.isDone());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
